<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .layout {
        padding-top: 20px;
        display: flex;
        width: 240px;
        justify-content: space-between;
      }
    </style>
  </head>
  <body>
    <div>
      <div class="layout">
        <button class="close">close</button>
        <button class="send">send</button>
        <button class="connect">connect</button>
      </div>
      <h2>Server Send Event测试</h2>
      <div><ul id="ul"></ul></div>
    </div>
    <script>
      let source = null;
      const url = "http://localhost:3000/keep";
      const closer = document.querySelector(".close");
      const sender = document.querySelector(".send");
      const ulDoom = document.querySelector("#ul");
      const connect = document.querySelector(".connect");

      function startConnect() {
        // EventSource对象只能发送GET请求，不能发送POST请求
        source = new EventSource(url, {
          headers: {
            Authorization: "Bearer your-token",
            "Custom-Header": "custom-value",
          },
        });
        source.addEventListener("open", () => {
          console.log("连接成功，等待接收数据");
        });
        source.addEventListener("message", (r) => {
          const child = document.createElement("li");
          child.innerHTML = r.data;
          console.log("获得的数据是:" + r.data);
          ulDoom.append(child);
        });
        source.addEventListener("error", (err) => {
          console.log(err);
        });
      }

      sender.addEventListener("click", () => {
        const salt = Date.now();
        fetch(`http://localhost:3000/send?salt=${salt}`)
          .then((r) => r.text())
          .then((r) => {
            console.log(r);
          });
      });

      closer.addEventListener("click", () => {
        source?.close();
      });

      connect.addEventListener("click", startConnect);
    </script>
  </body>
</html>
